package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.user.service.ApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    ApUserService userService;
    /**
     * 根据状态查询需要认证相关的用户信息
     * msg:完成单表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findListByStatus(AuthDto dto) {
        //第一步参数校验
        if(dto==null){
            //参数异常
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //第二部条件查询
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if(dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> pageParme=new Page<>(dto.getPage(), dto.getSize());
        IPage<ApUserRealname> page = page(pageParme, wrapper);
        //第三步封装结果并返回
        return new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal(),page.getRecords());
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult audit(AuthDto dto, Short status) {
        //1.检查参数
        if(dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取apUser id
        ApUserRealname userRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery().
                eq(ApUserRealname::getId, dto.getId()).
                eq(ApUserRealname::getStatus, AdminConstants.WAIT_AUDIT));
        if (userRealname==null||userRealname.getUserId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.UNABLE_OBTAIN_USER_MSG);
        }
        //2.1根据apUser.getId查询user的相关信息   这里默认了一个用户可以有多个自媒体账号
        ApUser apUser = userService.getOne(Wrappers.<ApUser>lambdaQuery().
                eq(ApUser::getId, userRealname.getUserId()).
                eq(ApUser::getFlag, AdminConstants.NORMAL_USER));

        if (apUser==null){
            //如果查询不出这个用户,用户不存在或者被锁定
            return ResponseResult.errorResult(AppHttpCodeEnum.NUMBER_DOTEXIT_OR_CLOSURE);
        }
        //3.修改状态
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);
        //4.如果审核沒有通过的话
        if(!AdminConstants.AUDIT_SUCCESS.equals(status)){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //如果审核通过的话
        //4.1远程创建自媒体账号
        WmUser wmUser =createMediaAccount(apUser);
        if (wmUser==null||wmUser.getApUserId()==null){
            CustException.cust(AppHttpCodeEnum.FAILD_CREATE_MEDIA);
        }
        //4.2远程创建作者账号
        boolean result=createAuthorAccount(wmUser);
        if(!result){
            //如果沒有創建成功抛出異常
            CustException.cust(AppHttpCodeEnum.FAILD_CREATE_AUTHOR);
        }
        //5.更新APuser数据中falg=1
        apUser.setFlag((short) 1);
        userService.updateById(apUser);
//        int i=1/0;
        //6.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Autowired
    ArticleFeign articleFeign;
    private boolean createAuthorAccount(WmUser wmUser) {
        //有作者的話就不用再次添加此作者
        ApAuthor userId = articleFeign.findByUserId(wmUser.getApUserId());
        if(userId==null){
            //如果这个值为空
            ApAuthor apAuthor=new ApAuthor();
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setName(wmUser.getName());
            apAuthor.setWmUserId(wmUser.getId());
            ResponseResult save = articleFeign.save(apAuthor);
            if(save.getCode()==0){
                return true;
            }
        }
        return false;
    }
    @Autowired
    WemediaFeign wemediaFeign;
    private WmUser createMediaAccount(ApUser apUser) {
        //有自媒体账号的话就不用
        WmUser byName = wemediaFeign.findByName(apUser.getName());
        if (byName==null){
            byName = new WmUser();
            byName.setName(apUser.getName());
            byName.setPhone(apUser.getPhone());
            byName.setPassword(apUser.getPassword());
            byName.setCreatedTime(new Date());
            byName.setSalt(apUser.getSalt());
            byName.setType(AdminConstants.PERSONAGE);
            byName.setApUserId(apUser.getId());  // app端用户id
            byName.setStatus(AdminConstants.AUDIT_SUCCESS);
            byName =  wemediaFeign.save(byName); // 主要的目的是返回新增后的主键
            if (byName.getId() != null) {
                return byName;
            }
        }
        return null;
    }

}
